package com.next

import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured
import static org.springframework.http.HttpStatus.*
import grails.converters.JSON
import groovy.json.JsonOutput

import java.text.SimpleDateFormat

@Secured(['ROLE_ADMINISTRATOR'])
@Transactional(readOnly = true)
class OpportunityController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max) 
    {
        if (params.status == 'Failed')
        {
            respond Opportunity.findAllByStatus('Failed', [sort: "modifiedDate", order: "desc", max: params.max ?: 10, offset: params.offset ?: 0]), model:[opportunityCount: Opportunity.countByStatus('Failed')], view: 'index'
            return
        }

        if (params.stage)
        {
            def sql = "from Opportunity o where o.status <> 'Failed' order by o.modifiedDate desc"
            // def sql = "from Opportunity o where o.status <> 'Failed' and o.stage.name like '%${params.stage}%' order by o.modifiedDate desc"
            def list = Opportunity.executeQuery(sql)
            respond list, model:[opportunityCount: list?.size()]
            return
        }

        respond Opportunity.findAll([sort: "modifiedDate", order: "desc", max: params.max ?: 10, offset: params.offset ?: 0]), model:[opportunityCount: Opportunity.count()], view: 'index'
        return
    }

    def show(Opportunity opportunity) {
        respond opportunity
    }

    def create() {
        respond new Opportunity(params)
    }

    @Transactional
    def save(Opportunity opportunity) {
        if (opportunity == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunity.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond opportunity.errors, view:'create'
            return
        }

        opportunity.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'opportunity.label', default: 'Opportunity'), opportunity.id])
                redirect opportunity
            }
            '*' { respond opportunity, [status: CREATED] }
        }
    }

    def edit(Opportunity opportunity) {
        respond opportunity
    }

    @Transactional
    def update(Opportunity opportunity) {
        if (opportunity == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunity.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond opportunity.errors, view:'edit'
            return
        }

        opportunity.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'opportunity.label', default: 'Opportunity'), opportunity.id])
                redirect opportunity
            }
            '*'{ respond opportunity, [status: OK] }
        }
    }

    @Transactional
    def delete(Opportunity opportunity) {

        if (opportunity == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        opportunity.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'opportunity.label', default: 'Opportunity'), opportunity.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'opportunity.label', default: 'Opportunity'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    @Secured(['permitAll'])
    @Transactional
    def welcome()
    {
        println "aaaaaaaaaaaaaaaaaaaaaaa"
        return
    }

    @Secured(['permitAll'])
    @Transactional
    def createOpportunity()
    {
        def json = request.JSON
        println "************************* createOpportunity ***************************"
        println json

        def openId = json['openId']
        def addressId = json['addressId']
        def unitPrice = json['unitPrice']?.toDouble()
        def totalPrice = json['totalPrice']?.toDouble()
        def purchaseCount = json['purchaseCount']?.toInteger()
        def productId = json['productId']
        def message = json['message']
        def date = json['date']
        def size = json['size']

        if (!openId || !Contact.findByOpenId(openId))
        {
            def errors = [errorCode: 2001, errorMessage: "请先完成登录"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        if (!addressId || !Address.findById(addressId))
        {
            def errors = [errorCode: 2002, errorMessage: "收货地址不能为空"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        if (!unitPrice)
        {
            def errors = [errorCode: 2003, errorMessage: "产品单价不能为空"]
            render JsonOutput.toJson(errors), status: 400
            return
        }
        
        if (!totalPrice)
        {
            def errors = [errorCode: 2004, errorMessage: "产品总价不能为空"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        if (!purchaseCount)
        {
            def errors = [errorCode: 2004, errorMessage: "购买数量不能为空"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        if (!productId || !Product.findById(productId))
        {
            def errors = [errorCode: 2005, errorMessage: "请选择产品"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        Date arrivalDate = null
        if (date && date != '请选择')
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
            arrivalDate = sdf.parse(date)
        }

        def opportunity = new Opportunity()
        opportunity.contact = Contact.findByOpenId(openId)
        opportunity.address = Address.findById(addressId)
        opportunity.unitPrice = unitPrice
        opportunity.totalPrice = totalPrice
        opportunity.quantity = purchaseCount
        opportunity.message = message
        opportunity.product = Product.findById(productId)
        opportunity.arrivalDate = arrivalDate
        if (size != 'null')
        {
            opportunity.size = size
        }

        if (opportunity.validate()) 
        {
            opportunity.save flush: true
        }
        else
        {
            println opportunity.errors
        }

        render opportunity as JSON
        return
    }

    @Secured(['permitAll'])
    def getOpportunityByOpenId()
    {
        def json = request.JSON
        println "************************* getOpportunityByOpenId ***************************"
        println json

        def openId = json['openId']
        if (!openId)
        {
            def errors = [errorCode: 2006, errorMessage: "请先完成登录"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        def contact = Contact.findByOpenId(openId)
        if (!contact)
        {
            def errors = [errorCode: 2007, errorMessage: "请先完成登录"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        render Opportunity.findAllByContact(contact, [sort: "modifiedDate", order: "desc"]) as JSON
        return
    }

    @Secured(['permitAll'])
    def getOpportunityDetailById()
    {
        def json = request.JSON
        println "************************* getOpportunityDetailById ***************************"
        println json

        def openId = json['openId']
        if (!openId)
        {
            def errors = [errorCode: 2008, errorMessage: "请先完成登录"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        def id = json['id']
        if (!id)
        {
            def errors = [errorCode: 2009, errorMessage: "订单标识不能为空"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        def opportunity = Opportunity.findById(id)
        if (!opportunity)
        {
            def errors = [errorCode: 2010, errorMessage: "订单标识不正确"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        // 订单创建时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        def createdDate = opportunity?.createdDate
        if (createdDate)
        {
            createdDate = sdf.format(createdDate)
        }
        
        // 订单送达时间
        sdf = new SimpleDateFormat("yyyy-MM-dd")
        def arrivalDate = opportunity?.arrivalDate
        if (arrivalDate)
        {
            arrivalDate = sdf.format(arrivalDate)
        }

        println createdDate
        println arrivalDate
        
        def retrunMap = [opportunity: opportunity, createdDate: createdDate, arrivalDate: arrivalDate]

        render retrunMap as JSON
        return
    }

    @Secured(['permitAll'])
    @Transactional
    def changOpportunityStatus(Opportunity opportunity)
    {
        opportunity.status = params['status']
        opportunity.save flush: true

        redirect controller: "opportunity", action: "show", method: "GET", id: opportunity?.id
        return
    }

    @Secured(['permitAll'])
    @Transactional
    def changOpportunityStage(Opportunity opportunity)
    {
        opportunity.stage = OpportunityStage.findByName(params['stage'])
        if (params['stage'] == '已完成')
        {
            opportunity.status = 'Completed'
        }

        opportunity.save flush: true

        redirect controller: "opportunity", action: "show", method: "GET", id: opportunity?.id
        return
    }

    @Secured(['permitAll'])
    def searchOpportunity()
    {

        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0;

        String sql = "from Opportunity as u where 1=1"
        def status = params['status']
        if (status)
        {
            sql += " and u.status like '%${status}%'"
        }

        def stage = params['stage']
        if (stage)
        {
            sql += " and u.stage.name like '%${stage}%'"
        }

        def serialNumber = params["serialNumber"]
        if (serialNumber)
        {
            sql += " and u.serialNumber like '%${serialNumber}%'"
        }

        def productName = params["productName"]
        if (productName)
        {
            sql += " and u.product.name like '%${productName}%'"
        }

        def fullName = params["fullName"]
        if (fullName)
        {
            sql += " and u.address.fullName like '%${fullName}%'"
        }

        def cellphone = params["cellphone"]
        if (cellphone)
        {
            sql += " and u.address.cellphone like '%${cellphone}%'"
        }

        def startTime = params["startTime"]
        def endTime = params["endTime"]
        if (startTime && endTime)
        {
            sql += " and u.createdDate between '${startTime}' and '${endTime}'"
        }

        sql += ' order by u.modifiedDate desc'

        println "sql:" + sql

        def max = params.max
        def offset = params.offset

        def list = Opportunity.findAll(sql, [max: max, offset: offset])
        def list1 = Opportunity.findAll(sql)
        def count = list1.size()

        respond list, model: [opportunityCount: count, params: params], view: 'index'
    }
}
